const path = require('path');
const { VueLoaderPlugin } = require('vue-loader')
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
const isDev = process.env.NOOE_ENV === 'development'
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const config = {
    target: 'web',
    entry: {
        app: path.join(__dirname, 'src/index.js'),
        vendor: ["vue"],
    },
    output: {
        filename: 'bundle.[hash:8].js',
        path: path.join(__dirname, 'dist'),
    },
    optimization: {
        runtimeChunk: 'single',
        splitChunks: {
            cacheGroups: {
                commons: {
                    name: "vendor",
                    chunks: "initial",
                    minChunks: 2
                }
            }
        }
    },
    mode: isDev ? 'development' : 'production',
    module: {

        rules: [
            {
                test: /\.vue$/,
                loader: 'vue-loader'
            },
            // this will apply to both plain .js files
            // AND <script> blocks in vue files
            {
                test: /\.js$/,
                loader: 'babel-loader'
            },

        ]
    },
    plugins: [
    // make sure to include the plugin for the magic
        new VueLoaderPlugin(),
        new HtmlWebpackPlugin({
            template: './index.html',
            filename: 'index.html'
        })
    ]

}

if(isDev) {
    config.devtool = 'cheap-eval-source-map'
    config.devServer = {
        port: 8080,
        host: 'localost',
        overlay: {
            errors: true
        },
        open: true,
        hot: true
    // historyFallback

    }
    config.module.rules.push(
    // this will apply to both plain .css files
    // AND <style> blocks in vue files
        {
            test: /\.css$/,
            use: [
                'vue-style-loader',
                'css-loader'
            ]
        })
    config.plugins.push(
        new webpack.NamedModulesPlugin(),
        new webpack.HotModuleReplacementPlugin(),

    )
}else{
    config.output.filename = '[name].[chunkhash:6].js'
    config.module.rules.push(
        {
            test: /\.css$/,
            use: ExtractTextPlugin.extract({
                fallback: "vue-style-loader",
                use: "css-loader"
            })
        }
    )

    config.plugins.push(
        new ExtractTextPlugin("styles.[chunkhash:8].css"),
    // new webpack.optimize.CommonsChunkPlugin({
    //   name: "vendor",
    //   minChunks: Infinity,
    // })

    )
}

module.exports = config;
